package com.xiaomacdut.oauthgithub.controller;

import com.xiaomacdut.oauthgithub.constant.SystemConstant;
import com.xiaomacdut.oauthgithub.model.Token;
import com.xiaomacdut.oauthgithub.util.HttpsUtil;
import org.apache.http.client.utils.HttpClientUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoma
 * @date 2020-04-21 17:33
 */
@Controller
@RequestMapping("/oauth/")
public class IndexController {

    private static final String  client_id="c20879847357d5630ae4";
    private static final String  client_secret="a1edce1e4991585a6595733076eb8d80cbf7001d";
    private static final String  ACCESSTOKEN_URL="https://github.com/login/oauth/access_token";
    private static final String  USER_INFO_URL="https://api.github.com/user";
    private static final String  redirect_uri="http://localhost:8080/oauth/redirect";
    /**
     * 参考：http://www.ruanyifeng.com/blog/2019/04/github-oauth.html
     * github授权地址：https://github.com/login/oauth/authorize?client_id='+${client_id}+'&redirect_uri='+${redirect_uri}
     * 1、前端请求该方法，跳转到index.html也没
     * 2、点击index.html页面的login链接，请求到github的授权地址
     * 3、github调用下面的redirect方法，也就是回调地址
     */
    @RequestMapping("")
    public String authorize(Model model){
        model.addAttribute("client_id",SystemConstant.CLIENT_ID);
        model.addAttribute("authorize_uri",SystemConstant.AUTHORIZE_URL);
        model.addAttribute("redirect_uri",redirect_uri);
        return "index";
    }

    /**
     * 1、回调地址：http://localhost:8080/oauth/redirect 需要在github中注册，让github知道回调地址是什么才能回调
     * 2、github调用回调地址时，携带code参数，如：http://localhost:8080/oauth/redirect?code=a00910c424a0d3c2c641
     * 3、通过code等参数，调用github的accesstoken地址，获取token。然后通过token就能获取到github账号的信息了
     * @param
     */
    @RequestMapping("redirect")
    @ResponseBody
    public  Object redirect(String code) throws Exception {
        String reqUrl=ACCESSTOKEN_URL+"?client_id="+client_id+"&client_secret="+client_secret+"&code="+code;
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<Token> responseEntity =  restTemplate.getForEntity(reqUrl, Token.class);
        Token token = responseEntity.getBody();
        System.out.println(token.getAccess_token());
        String result = HttpsUtil.get(USER_INFO_URL, token.getAccess_token(), null, null);
        return result;
    }

}
